<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef">
      <template #unitSlot="{ model, field }">
        <a-input-search :disabled="title === '详情'" v-model:value="model[field]" placeholder="请选择单位" readonly @search="unitOpen" />
      </template>
      <template #processManagement="{ model, field }">
       <a-input-search :disabled="title === '详情'" v-model:value="model[field]" placeholder="请选择加工工艺" readonly @search="processManagementOpen" />
      </template>
      <template #workshopSlot="{model,field}">
        <a-input-search :disabled="title === '详情'" v-model:value="model[field]" placeholder="请选择车间编码" readonly @search="handleAssociationCodeView" />
      </template>
      <template #useDepartment="{model,field}">
        <a-input-search :disabled="title === '详情'" v-model:value="model[field]" placeholder="请选择存放地点" readonly @search="handleUseDepartmentIdView" />
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="资源使用明细" key="basDeviceItem" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="basDeviceItem"
          :loading="basDeviceItemTable.loading"
          :columns="basDeviceItemTable.columns"
          :dataSource="basDeviceItemTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
        />
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 单位 -->
  <unitSelectModel @register="unitRegModal" @getSelectResult="unithandleSuccess" v-bind="getBindValue"></unitSelectModel>
  <basWarehouseSelectModel @register="regModal" @getSelectResult="handleSuccess" v-bind="getBindValue"></basWarehouseSelectModel>
  <!-- 加工工艺 -->
  <processManagementSelectModels @register="openProcessManagementModal" @getSelectResult="processManagementhandleSuccess" v-bind="getBindValue"></processManagementSelectModels>
  <!-- 工作中心 -->
  <workCenterListSelectModel @register="workCenterModal" @getSelectResult="handleWorkCenterValue" />
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
import { formSchema, basDeviceItemColumns } from '../BasDevice.data';
import { saveOrUpdate, basDeviceItemList } from '../BasDevice.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
// baseSetting/baseFiles/basWarehouseLocation/components/basWarehou
import basWarehouseSelectModel from '/@/views/baseSetting/baseFiles/basWarehouseLocation/components/basWarehouseSelectModel.vue';
import unitSelectModel from '/@/views/components/unitSelectModel.vue';
import processManagementSelectModels from '/@/views/components/processManagementSelectModels.vue';
import workCenterListSelectModel from '/@/views/components/workCenterListSelectModel.vue';


// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const staus = ref()
const formDisabled = ref(false);
const refKeys = ref(['basDeviceItem']);
const activeKey = ref('basDeviceItem');
const basDeviceItem = ref();
const tableRefs = { basDeviceItem };
const basDeviceItemTable = reactive({
  loading: false,
  dataSource: [],
  columns: basDeviceItemColumns,
});
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 8 },
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  staus.value = data.status
  formDisabled.value = !data?.showFooter;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    requestSubTableData(basDeviceItemList, { id: data?.record?.id }, basDeviceItemTable);
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter });
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);

//设置标题
const title = computed(() => staus.value);

// const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

async function reset() {
  await resetFields();
  activeKey.value = 'basDeviceItem';
  basDeviceItemTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    basDeviceItemList: allValues.tablesValue[0].tableData,
  };
}
//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
const getBindValue = Object.assign({}, '');
const [unitRegModal, { openModal: openUnitModal }] = useModal();
const [openProcessManagementModal, { openModal: processManagementModal }] = useModal();
const [workCenterModal, { openModal: openWorkCenterModal }] = useModal();
const [regModal, { openModal: openRegModal }] = useModal();
//单据类型
function unitOpen() {
  openUnitModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//单据类型回写
function unithandleSuccess(val, values) {
  setFieldsValue({
    unitName: val[0].label,
    unitId: val[0].value,
  });
}
function handleSuccess(val, values, type) {
  setFieldsValue({
    useDepartmentName: val[0].label,
    useDepartmentId: val[0].value,
  });
}
// 加工工艺
function processManagementOpen() {
  processManagementModal(true, {
    isUpdate: false,
    showFooter: true,
  });

}
// 工作中心
function handleAssociationCodeView(row: ResourceItem) {
  // operatFormItem.value = row

  openWorkCenterModal(true, {
    isUpdate: isUpdate.value,
    showFooter: true,
  });
}
const handleUseDepartmentIdView = () => {
  openRegModal(true,{
    isUpdate: isUpdate.value,
    showFooter: true,
  })
}
// 加工工艺选择
function processManagementhandleSuccess(val,values) {
  setFieldsValue({
    processManagementName: val[0].label,
    processManagementId: val[0].value,
    processManagementCode :val[0].item.processCoding
  });
}
function handleWorkCenterValue(value, _options) {
  setFieldsValue({
    workshopName: value[0].label,
    workshopId: value[0].value,
    workshopCode :value[0].item.workCenterCode
  });
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>